﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Linq;

using ECCIT;
using ECCIT.Data;
using ECCIT.Business.DAL;

using OgilvyOne.Utility;
using OgilvyOne.UKNow.Common;
using OgilvyOne.UKNow.Globalization;
using OgilvyOne.UKNow.Utility;
using OgilvyOne.UKNow.Model;
using OgilvyOne.UKNow.IDAL;

namespace OgilvyOne.UKNow.DAL
{
    public class NewsPhoneImageDAL : UKNowBaseDAL, IDALNewsPhoneImage
    {
        private const string TBL_NAME = "UKNOW_NEWS_PHONE_IMAGE";
        private const string COL_LANG_ID = "COL_LANG_ID";
        private const string COL_IMAGE_ID = "COL_IMAGE_ID";
        private const string COL_NEWS_ID = "COL_NEWS_ID";
        private const string COL_IMAGE_NAME = "COL_IMAGE_NAME";
        private const string COL_IMAGE_PATH = "COL_IMAGE_PATH";

        private const string COL_IMAGE_THUMB_PATH = "COL_IMAGE_THUMB_PATH";

        //private const string COL_EVENTS_IMAGE_AVATAR = "COL_EVENTS_IMAGE_AVATAR";
        private const string COL_IMAGE_EXT = "COL_IMAGE_EXT";
        private const string COL_IMAGE_DESC = "COL_IMAGE_DESC";
        private const string COL_IMAGE_TAG = "COL_IMAGE_TAG";
        private const string COL_IMAGE_STATE = "COL_IMAGE_STATE";
        private const string COL_IMAGE_ORDER = "COL_IMAGE_ORDER";
        private const string COL_IMAGE_RECO = "COL_IMAGE_RECO";
        private const string COL_IMAGE_INSERT_TIME = "COL_IMAGE_INSERT_TIME";
        private const string COL_IMAGE_UPDATE_TIME = "COL_IMAGE_UPDATE_TIME";

        public override string TableName { get { return TBL_NAME; } }

        public override Type ModelType { get { return typeof(EventsImageModel); } }

        [PrimaryKey]
        public IField LanguageID { get { return FieldFactory.Create(ModelType, "LanguageID", ColumnFactory.CreateColumn(COL_LANG_ID, DataType.Int)); } }
        [PrimaryKey]
        public IField ID { get { return FieldFactory.Create(ModelType, "ID", ColumnFactory.CreateColumn(COL_IMAGE_ID, DataType.Int)); } }
        public IField EventsID { get { return FieldFactory.Create(ModelType, "EventsID", ColumnFactory.CreateColumn(COL_NEWS_ID, DataType.Int)); } }
        public IField Name { get { return FieldFactory.Create(ModelType, "Name", ColumnFactory.CreateColumn(COL_IMAGE_NAME, DataType.String, 200)); } }
        public IField Path { get { return FieldFactory.Create(ModelType, "Path", ColumnFactory.CreateColumn(COL_IMAGE_PATH, DataType.String, 200)); } }
        //mff
        public IField Path1 { get { return FieldFactory.Create(ModelType, "Path1", ColumnFactory.CreateColumn(COL_IMAGE_THUMB_PATH, DataType.String, 200)); } }
        //mff
        //public IField Avatar { get { return FieldFactory.Create(ModelType, "Avatar", ColumnFactory.CreateColumn(COL_EVENTS_IMAGE_AVATAR, DataType.String, 200)); } }
        public IField Extension { get { return FieldFactory.Create(ModelType, "Extension", ColumnFactory.CreateColumn(COL_IMAGE_EXT, DataType.String, 20)); } }
        public IField Description { get { return FieldFactory.Create(ModelType, "Description", ColumnFactory.CreateColumn(COL_IMAGE_DESC, DataType.String, 500)); } }
        public IField Tag { get { return FieldFactory.Create(ModelType, "Tag", ColumnFactory.CreateColumn(COL_IMAGE_TAG, DataType.String, 200)); } }
        public IField State { get { return FieldFactory.Create(ModelType, "State", ColumnFactory.CreateColumn(COL_IMAGE_STATE, DataType.Int)); } }
        public IField Order { get { return FieldFactory.Create(ModelType, "Order", ColumnFactory.CreateColumn(COL_IMAGE_ORDER, DataType.Int)); } }
        public IField IsRecommendation { get { return FieldFactory.Create(ModelType, "IsRecommendation", ColumnFactory.CreateColumn(COL_IMAGE_RECO, DataType.Bit)); } }
        public IField InsertedTime { get { return FieldFactory.Create(ModelType, "InsertedTime", ColumnFactory.CreateColumn(COL_IMAGE_INSERT_TIME, DataType.DateTime)); } }
        public IField UpdatedTime { get { return FieldFactory.Create(ModelType, "UpdatedTime", ColumnFactory.CreateColumn(COL_IMAGE_UPDATE_TIME, DataType.DateTime)); } }
        //mff
        public override IField[] InsertFields { get { return new IField[] { LanguageID, ID, EventsID, Name, Path, Path1, Extension, Description, Tag, State, Order, IsRecommendation, InsertedTime, UpdatedTime }; } }
        public override IField[] SelectFields { get { return InsertFields; } }
        //mff
        public override IField[] UpdateFields { get { return new IField[] { LanguageID, ID, EventsID, Name, Path, Path1, Extension, Description, Tag, State, Order, IsRecommendation, UpdatedTime }; } }

        public NewsPhoneImageDAL() { }

        public NewsPhoneImageDAL(LanguageType languageType) { this.Language = LanguageFactory.Create(languageType); }

        //private void SetForeignKeyModel(EventsImageModel model)
        //{
        //    if (model == null) return;
        //    //model.FileType = 1;
        //    model.ThumbnailImagePath = model.Path1;
        //    model.News = new EventsDAL(this.Language.LanguageType).GetEventsModelByID(model.NewsID);
        //}

        #region IDALEventsImage Members
        //获得一个图片
        public EventsImageModel GetNewsPhoneImageModelByID(int? id)
        {
            EventsImageModel model = (EventsImageModel)GetModelByPrimaryKey(this.GetType(), new KeyValuePair<IField, object>[] { new KeyValuePair<IField, object>(LanguageID, (int)this.Language.LanguageType), new KeyValuePair<IField, object>(this.ID, id) });
            //SetForeignKeyModel(model);
            return model;
        }
        //一个新闻的多个图片
        public IList<EventsImageModel> GetAllNewsPhoneImageModels(int? newsID)
        {
            IDataParameter[] parms = DBHelper.GetDataParameters(new IField[] { EventsID, LanguageID });
            parms[0].Value = newsID;
            parms[1].Value = (int)this.Language.LanguageType;

            string whereClause = "WHERE " + COL_NEWS_ID + "=#" + COL_NEWS_ID + " AND " + COL_LANG_ID + "=#" + COL_LANG_ID;

            IList<EventsImageModel> models = GetModels(whereClause, PagingParameterFactory.CreateNonPagingParameter(SortingParameterFactory.CreateInstance(UpdatedTime.PropertyName, SortOrder.Desc)), parms).List.Cast<EventsImageModel>().ToList();
            //foreach (EventsImageModel model in models)
                //SetForeignKeyModel(model);

            return models;
        }
        public IList<EventsImageModel> GetPublishedNewsImageModels(int? newsID)
        {
            WhereClauseBuilder builder = WhereClauseBuilder.CreateInstance(SearchConditionJoinOperator.AND);
            builder.Conditions.Add(CommonSearchCondition.CreateInstance(COL_IMAGE_STATE, 1, SearchConditionOperator.Equals));
            builder.Conditions.Add(CommonSearchCondition.CreateInstance(COL_NEWS_ID, newsID, SearchConditionOperator.Equals));
            builder.Conditions.Add(CommonSearchCondition.CreateInstance(COL_LANG_ID, (int)this.Language.LanguageType, SearchConditionOperator.Equals));

            string whereClause = builder.ToSqlCommand();
            IList<EventsImageModel> models = GetModels(whereClause, PagingParameterFactory.CreateNonPagingParameter(SortingParameterFactory.CreateInstance(Order.PropertyName + "," + UpdatedTime.PropertyName, SortOrder.Desc))).List.Cast<EventsImageModel>().ToList();

            //foreach (EventsImageModel model in models)
                //SetForeignKeyModel(model);
            return models;
        }
        //根据新闻ID修改活动图片的发布状态的方法
        public bool editPubState(int nid)
        {
            string sqlstr = string.Format("update dbo.UKNOW_NEWS_IMAGE set COL_IMAGE_STATE =0 where COL_LANG_ID={0} and COL_NEWS_ID={1}", (int)this.Language.LanguageType, nid);
            int i = DBHelper.ExecuteNonQuery(sqlstr);
            if (i > 0)
            { return true; }
            else
            { return false; }
        }
        public ResultInfo Save(EventsImageModel modelInfo)
        {
            if (modelInfo == null) throw new ArgumentNullException("modelInfo");

            ResultInfo result = new ResultInfo(false);

            try
            {
                int rowsAffected = 0;
                if (modelInfo.ID == null)   // insert
                {
                    modelInfo.ID = SqlUtil.GetMaxRecordID(TableName, COL_IMAGE_ID, COL_LANG_ID, (int)this.Language.LanguageType);
                    //modelInfo.State = 0;    // 强制将图片状态置为未发布
                    modelInfo.InsertedTime = DateTime.Now;
                    modelInfo.UpdatedTime = DateTime.Now;
                    rowsAffected = Insert(modelInfo, null);
                }
                else // update
                {
                    modelInfo.UpdatedTime = DateTime.Now;
                    rowsAffected = UpdateByPrimaryKey(modelInfo, null);
                }

                if (rowsAffected > 0)
                {
                    result.Message = "图片数据保存成功！";
                    result.Result = true;
                    result.ReturnObject = modelInfo;
                }
            }
            catch (Exception ex)
            {
                result.Exception = ex;
                result.Message = string.Format("保存手机图片数据时发生异常。异常信息：{0}", ex.Message);
            }

            return result;
        }
        public ResultInfo Delete(IList<int?> idList)
        {
            ResultInfo result = new ResultInfo(false);
            using (IDbConnection conn = DBHelper.GetDbConnection())
            {
                conn.Open();
                IDbTransaction trans = conn.BeginTransaction();
                try
                {
                    foreach (int? id in idList)
                        DeleteModelByPrimaryKey(trans, this.GetType(), new KeyValuePair<IField, object>[] { new KeyValuePair<IField, object>(LanguageID, (int)this.Language.LanguageType), new KeyValuePair<IField, object>(this.ID, id) });

                    trans.Commit();
                    result.Result = true;
                    result.Message = "手机图片数据删除成功！";
                }
                catch (Exception ex)
                {
                    trans.Rollback();
                    result.Message = string.Format("删除手机图片数据时发生异常。异常信息：{0}", ex.Message);
                }
                finally
                {
                    trans.Dispose();
                }
            }

            return result;
        }
        public ResultInfo Publish(IList<int?> idList)
        {
            ResultInfo result = new ResultInfo(false);

            IField[] updatedFields = new IField[] { this.State };
            IDataParameter[] parms = DBHelper.GetDataParameters(updatedFields);
            parms[0].Value = 1;

            string ids = "";
            foreach (int? id in idList)
                ids += (ids == string.Empty) ? id.ToString() : "," + id.ToString();

            WhereClauseBuilder builder = WhereClauseBuilder.CreateInstance(SearchConditionJoinOperator.AND);
            builder.Conditions.Add(InSearchCondition.CreateInstance(COL_IMAGE_ID, DataType.Int, ids));
            builder.Conditions.Add(CommonSearchCondition.CreateInstance(COL_LANG_ID, (int)this.Language.LanguageType, SearchConditionOperator.Equals));

            string whereClause = builder.ToSqlCommand();
            string cmdText = DBHelper.GetUpdateCommandText(this.TableName, updatedFields, whereClause);

            try
            {
                DBHelper.ExecuteNonQuery(cmdText, parms);
                result.Result = true;
                result.Message = "图片发布成功！";
            }
            catch (Exception ex)
            {
                result.Message = string.Format("发布图片时发生异常。异常信息：{0}", ex.Message);
            }

            return result;
        }

        public ResultInfo UnPublish(IList<int?> idList)
        {
            ResultInfo result = new ResultInfo(false);

            IField[] updatedFields = new IField[] { this.State };
            IDataParameter[] parms = DBHelper.GetDataParameters(updatedFields);
            parms[0].Value = 0;

            string ids = "";
            foreach (int? id in idList)
                ids += (ids == string.Empty) ? id.ToString() : "," + id.ToString();

            WhereClauseBuilder builder = WhereClauseBuilder.CreateInstance(SearchConditionJoinOperator.AND);
            builder.Conditions.Add(InSearchCondition.CreateInstance(COL_IMAGE_ID, DataType.Int, ids));
            builder.Conditions.Add(CommonSearchCondition.CreateInstance(COL_LANG_ID, (int)this.Language.LanguageType, SearchConditionOperator.Equals));

            string whereClause = builder.ToSqlCommand();
            string cmdText = DBHelper.GetUpdateCommandText(this.TableName, updatedFields, whereClause);

            try
            {
                DBHelper.ExecuteNonQuery(cmdText, parms);
                result.Result = true;
                result.Message = "图片取消发布成功！";
            }
            catch (Exception ex)
            {
                result.Message = string.Format("取消发布图片时发生异常。异常信息：{0}", ex.Message);
            }

            return result;
        }
        //public IList<EventsImageModel> GetAllPublishedPhoneNewsRecoImageModels()
        //{

        //    WhereClauseBuilder builder = WhereClauseBuilder.CreateInstance(SearchConditionJoinOperator.AND);
        //    builder.Conditions.Add(CommonSearchCondition.CreateInstance(COL_IMAGE_STATE, 1, SearchConditionOperator.Equals));
        //    builder.Conditions.Add(CommonSearchCondition.CreateInstance(COL_IMAGE_RECO, 1, SearchConditionOperator.Equals));
        //    builder.Conditions.Add(CommonSearchCondition.CreateInstance(COL_LANG_ID, (int)this.Language.LanguageType, SearchConditionOperator.Equals));
        //    string whereClause = builder.ToSqlCommand();
        //    IList<EventsImageModel> models = GetModels(whereClause, PagingParameterFactory.CreateNonPagingParameter(SortingParameterFactory.CreateInstance(UpdatedTime.PropertyName, SortOrder.Desc))).List.Cast<EventsImageModel>().ToList();

        //    foreach (EventsImageModel model in models)
        //        SetForeignKeyModel(model);
        //    return models;
        //}
        #endregion
    }
}
